<template>
  <div class="mileage-detail-page">

    <van-nav-bar title="我的骑行" left-text="返回" left-arrow @click-left="router.back()" fixed />
    <!-- 总数据展示 -->
    <div class="data-card total-stats">
      <div class="total-stat">
        <div class="stat-value">{{ rideData?.rideMileageTotal || '0' }}<span class="unit">km</span></div>
        <div class="stat-label">总里程数</div>
      </div>
      <div class="stat-divider"></div>
      <div class="total-stat">
        <div class="stat-value">{{ rideData?.bendingTimesToal || '0' }}<span class="unit">次</span></div>
        <div class="stat-label">压弯</div>
      </div>
    </div>

    <!-- 月份统计图表 -->
    <div class="data-card chart-section">
      <div class="month-selector">
        <div class="month-arrow" @click="changeMonth(-1)">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="15 18 9 12 15 6"></polyline>
          </svg>
        </div>
        <div class="current-month">{{ currentMonth }}</div>
        <div class="month-arrow" @click="changeMonth(1)">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="9 18 15 12 9 6"></polyline>
          </svg>
        </div>
      </div>

      <!-- 折线图 -->
      <div class="chart-container">
        <div v-if="loading" class="loading-chart">
          <div class="loading-spinner"></div>
          <div>加载数据中...</div>
        </div>
        <div v-else-if="!hasData" class="no-data">暂无骑行数据</div>
        <div v-else class="chart" ref="chartRef"></div>
      </div>
    </div>

    <!-- 当日骑行数据 -->
    <div class="data-card day-data">
      <div class="card-header">
        <div class="section-title">当日数据</div>
        <div class="card-date">{{ formatSelectedDate() }}</div>
      </div>

      <!-- 第一行骑行数据 -->
      <div class="day-stats-row">
        <div class="day-stat">
          <div class="day-stat-value">{{ rideData?.rideMileageDay || '0' }}<span class="unit">km</span></div>
          <div class="day-stat-label">总里程数</div>
        </div>
        <div class="day-stat">
          <div class="day-stat-value">{{ rideData?.ridingTimeDayUnitMinute || '0' }}<span class="unit">min</span></div>
          <div class="day-stat-label">时长</div>
        </div>
        <div class="day-stat">
          <div class="day-stat-value">{{ rideData?.maxSpeed || '0' }}<span class="unit">km/h</span></div>
          <div class="day-stat-label">最高速度</div>
        </div>
      </div>

      <!-- 第二行骑行数据 -->
      <div class="day-stats-row">
        <div class="day-stat">
          <div class="day-stat-value">{{ rideData?.accelerationTimesDay || '0' }}<span class="unit">次</span></div>
          <div class="day-stat-label">加速</div>
        </div>
        <div class="day-stat">
          <div class="day-stat-value">{{ rideData?.brakesTimesDay || '0' }}<span class="unit">次</span></div>
          <div class="day-stat-label">急刹</div>
        </div>
        <div class="day-stat">
          <div class="day-stat-value">{{ rideData?.bendingTimesDay || '0' }}<span class="unit">次</span></div>
          <div class="day-stat-label">压弯</div>
        </div>
      </div>
    </div>

    <!-- 骑行能力雷达图 -->
    <div class="data-card radar-chart-section">
      <div class="card-header">
        <div class="section-title">当月骑行分析</div>
        <div class="share-button" @click="showShareModal = true">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"></path>
            <polyline points="16 6 12 2 8 6"></polyline>
            <line x1="12" y1="2" x2="12" y2="15"></line>
          </svg>
          分享
        </div>
      </div>

      <div class="radar-container">
        <div ref="radarChartRef" class="radar-chart"></div>
      </div>
      <div class="chart-description">基于您本月的骑行数据生成</div>
    </div>

    <!-- 分享预览弹窗 -->
    <van-popup v-model:show="showShareModal" round position="bottom" :style="{ height: '85%' }" class="share-popup">
      <div class="share-header">
        <div class="share-title">骑行分享</div>
        <div class="close-button" @click="showShareModal = false">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </div>
      </div>

      <div class="share-content">
        <div class="preview-container" ref="previewContainerRef">
          <div class="preview-image-container" ref="sharePreviewRef">
            <div class="preview-header">
              <div class="preview-title">骑行分析</div>
              <div class="vehicle-block">
            
                <div class="right">
                  <div class="user-info">
                    <div class="avatar-wrap">
                      <img v-if="userAvatar" class="user-avatar" :src="userAvatar" alt="avatar" @error="onAvatarError"
                        ref="avatarImgRef" crossorigin="anonymous" />
                      <div v-else class="avatar-fallback">{{ userInitials }}</div>
                    </div>
                    <div class="user-meta">
                      <div class="user-name">
                        {{ userNickname }}
                      </div>
                    </div>
                  </div>
                </div>
                <div class="left">
                  <img class="preview-vehicle-img" :src="vehicleImage" ref="vehicleImgRef" crossorigin="anonymous" />

                  <div class="preview-vehicle">{{ currentVehicle?.vehicleName || '我的爱车' }}</div>
                </div>
              </div>
              <div class="meta-line">
                <span class="pill">{{ currentMonth }}</span>
                <span class="dot"></span>
                <span class="vin">VIN：{{ currentVehicle?.vinNo || '-' }}</span>
              </div>
            </div>
            <div class="highlight-stats">
              <div class="h-item">
                <svg viewBox="0 0 24 24" class="h-ic">
                  <path fill="currentColor" d="M12 2a10 10 0 1 0 .001 20.001A10 10 0 0 0 12 2Zm1 11H7v-2h4V7h2v6Z" />
                </svg>
                <div class="h-text"><b>{{ calculateMonthlyMileage() }}</b><span> km 本月里程</span></div>
              </div>
              <div class="h-item">
                <svg t="1756805242461" class="icon" viewBox="0 0 1024 1024" version="1.1"
                  xmlns="http://www.w3.org/2000/svg" p-id="10226" width="20" height="20">
                  <path
                    d="M869.56032 365.64992l-52.49024 78.92992a341.34016 341.34016 0 0 1-9.37984 323.42016H216.33024a341.31968 341.31968 0 0 1 448.43008-475.72992l78.92992-52.46976A426.65984 426.65984 0 0 0 142.9504 810.65984a85.31968 85.31968 0 0 0 73.37984 42.68032h590.92992a85.34016 85.34016 0 0 0 74.24-42.68032 426.68032 426.68032 0 0 0-11.53024-445.44l-0.4096 0.43008z m-417.71008 291.84a85.2992 85.2992 0 0 0 120.75008 0L814.08 295.26016 451.85024 536.73984a85.31968 85.31968 0 0 0 0 120.75008z"
                    fill="currentColor" p-id="10227"></path>
                </svg>

                <div class="h-text"><b>{{ rideData?.maxSpeedMonth || rideData?.maxSpeed || '0' }}</b><span> km/h 最高速度</span></div>
              </div>
            </div>
            <div class="preview-chart-container" ref="previewChartRef"></div>
            <div class="preview-footer">
              <img class="footer-logo" :src="defaultVehicleImg" alt="logo" />
              <span>慢牛电控 · @谦虚</span>
            </div>
          </div>
        </div>
        <div class="share-actions">
          <van-button type="primary" block @click="saveImage">保存图片</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showLoadingToast, closeToast, showFailToast, showSuccessToast, Button as VanButton } from 'vant';
import { useVehicleStore } from '@/stores/vehicle';
import { useUserStore } from '@/stores/user';
import { getMileageDetail, getRideMonthInfo, getRidingDetail } from '@/api/vehicle';
import * as echarts from 'echarts/core';
import { BarChart, RadarChart } from 'echarts/charts';
import { GridComponent, TooltipComponent, MarkPointComponent, DataZoomComponent, LegendComponent, TitleComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import html2canvas from 'html2canvas';
import defaultVehicleImg from '@/assets/logo.png';

// 注册ECharts需要的组件
echarts.use([
  BarChart,
  RadarChart,
  GridComponent,
  TooltipComponent,
  MarkPointComponent,
  DataZoomComponent,
  LegendComponent,
  TitleComponent,
  CanvasRenderer
]);

const router = useRouter();
const route = useRoute();
const vehicleStore = useVehicleStore();
const userStore = useUserStore();

// 当前车辆
const currentVehicle = computed(() => vehicleStore.getCurrentVehicle());

// 车辆图片
const vehicleImage = computed(() => {
  const v = currentVehicle.value || {};
  return v.customImage || v.custom_image || v.vehiclePicUrl || v.vehicleScalePicUrl || v.vehicleBackPicUrl || defaultVehicleImg;
});

// 用户信息（优先使用 Pinia userStore，其次回退）
const userNickname = computed(() => {
  const u = userStore?.userInfo?.userData || {};
  return (
    u.nickname || u.nickName || u.name || u.username || u.userName || '骑士'
  );
});

const userAvatar = computed(() => {
  const u = userStore?.userInfo?.userData || {};
  return (
    u.avatar || u.avatarUrl || u.headImg || u.headImage || u.headPortrait || defaultVehicleImg
  );
});

// 用户名首字母（或汉字首字符）
const userInitials = computed(() => {
  const name = String(userNickname.value || '').trim();
  if (!name) return '骑';
  // 取前2字符，英文取前2，中文常取首字
  const first = name[0];
  if (/^[A-Za-z]$/.test(first) && name.length > 1 && /^[A-Za-z]$/.test(name[1])) {
    return (first + name[1]).toUpperCase();
  }
  return first;
});

// 头像加载失败回退
const onAvatarError = (e) => {
  try {
    e.target.src = '';
  } catch (_) { }
};

// 图表相关
const chartRef = ref(null);
const chartInstance = ref(null);
const loading = ref(true);
const hasData = ref(false);
const rideData = ref(null);

// 雷达图相关
const radarChartRef = ref(null);
let radarChartInstance = null;
const previewChartRef = ref(null);
let previewChartInstance = null;

// 窗口自适应处理（定义为独立函数，便于解绑）
const onResize = () => {
  if (chartInstance.value) {
    chartInstance.value.resize();
  }
  if (radarChartInstance) {
    radarChartInstance.resize();
  }
  if (previewChartInstance) {
    previewChartInstance.resize?.();
  }
};

// 分享相关
const showShareModal = ref(false);
const sharePreviewRef = ref(null);
const previewContainerRef = ref(null);
const vehicleImgRef = ref(null);
const avatarImgRef = ref(null);

// 月份选择相关
const now = new Date();
const currentYear = ref(now.getFullYear());
const currentMonthIndex = ref(now.getMonth());
const currentMonth = computed(() => {
  return `${currentYear.value}.${String(currentMonthIndex.value + 1).padStart(2, '0')}`;
});

// 选中日期
const selectedDate = ref(null);
const selectedDayIndex = ref(-1);

// 获取里程数据
const fetchMileageData = async () => {
  if (!currentVehicle.value?.vinNo) return;

  loading.value = true;



  try {
    const response = await getMileageDetail(currentVehicle.value.vinNo);

    if (response && response.data) {
      // 保存完整的骑行数据
      rideData.value = response.data;

      hasData.value = rideData.value.rideRocordList && rideData.value.rideRocordList.length > 0;

      // 默认选中最新一天
      if (hasData.value && rideData.value.rideRocordList.length > 0) {
        selectedDayIndex.value = rideData.value.rideRocordList.length - 1;
        selectedDate.value = rideData.value.rideRocordList[selectedDayIndex.value].date;
      }

      nextTick(() => {
        initChart();
      });
    } else {
      hasData.value = false;
      showFailToast('数据获取失败');
    }
  } catch (error) {
    console.error('获取里程数据失败:', error);
    hasData.value = false;

    // 模拟数据
    rideData.value = {
      rideMileageTotal: "5089",
      bendingTimesToal: "0",
      greenContribution: "343.5",
      fate: "2133",
      rideMileageDay: "24.0",
      greenContributionDay: "1.6",
      ridingTimeDay: "0.9",
      ridingTimeDayUnitMinute: "58",
      bendingTimesDay: "0",
      maxSpeed: "66.6",
      accelerationTimesDay: "36",
      brakesTimesDay: "26",
      powerConsumptionDay: "0",
      rideRocordList: [
        { date: "2025.08.01", rideMileage: "47.7" },
        { date: "2025.08.02", rideMileage: "8.5" },
        { date: "2025.08.03", rideMileage: "45.8" },
        { date: "2025.08.04", rideMileage: "47.7" },
        { date: "2025.08.05", rideMileage: "47.8" },
        { date: "2025.08.06", rideMileage: "47.8" },
        { date: "2025.08.07", rideMileage: "47.7" },
        { date: "2025.08.08", rideMileage: "47.9" },
        { date: "2025.08.09", rideMileage: "53.6" },
        { date: "2025.08.10", rideMileage: "48.2" },
        { date: "2025.08.11", rideMileage: "24.0" }
      ]
    };

    hasData.value = true;
    selectedDayIndex.value = rideData.value.rideRocordList.length - 1;
    selectedDate.value = rideData.value.rideRocordList[selectedDayIndex.value].date;

    nextTick(() => {
      initChart();
    });
  } finally {
    loading.value = false;
    closeToast();
  }
};

// 切换月份
const changeMonth = async (direction) => {
  // 更新月份
  currentMonthIndex.value += direction;

  // 处理年份变化
  if (currentMonthIndex.value < 0) {
    currentMonthIndex.value = 11;
    currentYear.value -= 1;
  } else if (currentMonthIndex.value > 11) {
    currentMonthIndex.value = 0;
    currentYear.value += 1;
  }

  // 重新加载月份数据
  fetchMonthData();
};

// 获取月度数据
const fetchMonthData = async () => {
  if (!currentVehicle.value?.vinNo) return;

  loading.value = true;

  try {
    const response = await getRideMonthInfo(
      currentVehicle.value.vinNo,
      currentMonth.value
    );

    if (response && response.data) {
      // 保存月度骑行记录
      const monthData = response.data || [];

      if (monthData.length > 0) {
        hasData.value = true;

        // 更新图表数据但保留其他信息
        if (rideData.value) {
          rideData.value = {
            ...rideData.value,
            rideRocordList: monthData
          };
        } else {
          rideData.value = {
            rideMileageTotal: "0",
            bendingTimesToal: "0",
            rideRocordList: monthData
          };
        }

        // 默认选中最新一天
        selectedDayIndex.value = monthData.length - 1;
        selectedDate.value = monthData[selectedDayIndex.value].date;

        // 计算整月聚合数据（调用日详情并聚合）
        try {
          const agg = await aggregateMonthDetails(monthData.map(d => d.date));
          // 写入用于雷达图的月度字段
          rideData.value = {
            ...rideData.value,
            maxSpeedMonth: agg.maxSpeed.toFixed(0),
            avgVelocityMonth: agg.avgSpeed.toFixed(1),
            rideMileageMonth: agg.totalMileage.toFixed(1),
            ridingTimeMonthUnitMinute: agg.totalMinutes.toFixed(0),
            bendingTimesMonth: agg.totalBending.toFixed(0),
            accelerationTimesMonth: agg.totalAcceleration.toFixed(0)
          };
        } catch (e) {
          // 聚合失败不阻塞页面
          console.warn('月度聚合失败，使用基础数据:', e);
        }

        // 同时刷新选中日期的当日数据（用于“当日数据”卡片）
        await fetchDayData(selectedDate.value);
      } else {
        hasData.value = false;
        showFailToast('该月暂无骑行数据');
      }
    } else {
      hasData.value = false;
      showFailToast('获取月度数据失败');
    }
  } catch (error) {
    console.error('获取月度数据失败:', error);
    hasData.value = false;

    // 模拟数据
    const daysInMonth = new Date(currentYear.value, currentMonthIndex.value + 1, 0).getDate();
    const mockMonthData = Array(daysInMonth).fill().map((_, i) => {
      const day = i + 1;
      return {
        date: `${currentYear.value}.${String(currentMonthIndex.value + 1).padStart(2, '0')}.${String(day).padStart(2, '0')}`,
        rideMileage: Math.random() > 0.2 ? (Math.random() * 40 + 10).toFixed(1) : (Math.random() * 10).toFixed(1)
      };
    });

    if (rideData.value) {
      rideData.value = {
        ...rideData.value,
        rideRocordList: mockMonthData
      };
    } else {
      rideData.value = {
        rideMileageTotal: "0",
        bendingTimesToal: "0",
        rideRocordList: mockMonthData
      };
    }

    hasData.value = true;

    // 默认选中最新一天
    selectedDayIndex.value = mockMonthData.length - 1;
    selectedDate.value = mockMonthData[selectedDayIndex.value].date;
  } finally {
    loading.value = false;
    closeToast();

    // 初始化图表
    nextTick(() => {
      initChart();
    });
  }
};

// 并发限制执行器
const pLimit = (limit) => {
  let running = 0;
  const queue = [];
  const next = () => {
    if (running >= limit || queue.length === 0) return;
    running++;
    const { fn, resolve, reject } = queue.shift();
    fn().then((v) => { resolve(v); }).catch(reject).finally(() => { running--; next(); });
  };
  return (fn) => new Promise((resolve, reject) => { queue.push({ fn, resolve, reject }); next(); });
};

// 汇总某月每天详情，生成月度聚合
const aggregateMonthDetails = async (dateList = []) => {
  if (!currentVehicle.value?.vinNo || !Array.isArray(dateList) || dateList.length === 0) {
    return { totalMileage: 0, totalMinutes: 0, maxSpeed: 0, totalBending: 0, totalAcceleration: 0, avgSpeed: 0 };
  }
  const limitRun = pLimit(5); // 控制并发，避免压垮接口

  const results = await Promise.allSettled(dateList.map(date => limitRun(async () => {
    const res = await getRidingDetail(currentVehicle.value.vinNo, date);
    return res?.data || {};
  })));

  let totalMileage = 0;
  let totalMinutes = 0;
  let maxSpeed = 0;
  let totalBending = 0;
  let totalAcceleration = 0;

  // 补：里程从月列表中更准确，先计算
  if (rideData.value?.rideRocordList?.length) {
    totalMileage = rideData.value.rideRocordList.reduce((s, i) => s + parseFloat(i.rideMileage || 0), 0);
  }

  results.forEach(r => {
    if (r.status !== 'fulfilled') return;
    const d = r.value;
    const min = parseFloat(d.ridingTimeDayUnitMinute || 0);
    const spd = parseFloat(d.maxSpeed || 0);
    const bend = parseFloat(d.bendingTimesDay || 0);
    const acc = parseFloat(d.accelerationTimesDay || 0);
    totalMinutes += isNaN(min) ? 0 : min;
    maxSpeed = Math.max(maxSpeed, isNaN(spd) ? 0 : spd);
    totalBending += isNaN(bend) ? 0 : bend;
    totalAcceleration += isNaN(acc) ? 0 : acc;
  });

  const hours = totalMinutes / 60;
  const avgSpeed = hours > 0 ? (totalMileage / hours) : 0;

  return { totalMileage, totalMinutes, maxSpeed, totalBending, totalAcceleration, avgSpeed };
};

// 确保本月聚合字段已就绪（供雷达图与分享预览使用）
const ensureMonthAggregates = async () => {
  try {
    // 需要日期列表来汇总
    const dates = rideData.value?.rideRocordList?.map(d => d.date) || [];
    if (!dates.length) return;

    // 若字段已存在且有效，可按需跳过；为稳妥起见，这里每次打开分享前都会刷新
    const agg = await aggregateMonthDetails(dates);

    rideData.value = {
      ...rideData.value,
      maxSpeedMonth: Number(agg.maxSpeed || 0).toFixed(0),
      avgVelocityMonth: Number(agg.avgSpeed || 0).toFixed(1),
      rideMileageMonth: Number(agg.totalMileage || 0).toFixed(1),
      ridingTimeMonthUnitMinute: Number(agg.totalMinutes || 0).toFixed(0),
      bendingTimesMonth: Number(agg.totalBending || 0).toFixed(0),
      accelerationTimesMonth: Number(agg.totalAcceleration || 0).toFixed(0)
    };
  } catch (e) {
    console.warn('ensureMonthAggregates 计算失败：', e);
  }
};

// 获取特定日期的骑行数据
const fetchDayData = async (date) => {
  if (!currentVehicle.value?.vinNo || !date) return;

  try {
    const response = await getRidingDetail(
      currentVehicle.value.vinNo,
      date
    );

    if (response && response.data) {
      // 更新当日数据
      const dayData = response.data;

      // 更新rideData中的当日数据字段
      rideData.value = {
        ...rideData.value,
        rideMileageDay: dayData.rideMileageDay || '0',
        ridingTimeDayUnitMinute: dayData.ridingTimeDayUnitMinute || '0',
        maxSpeed: dayData.maxSpeed || '0',
        accelerationTimesDay: dayData.accelerationTimesDay || '0',
        brakesTimesDay: dayData.brakesTimesDay || '0',
        bendingTimesDay: dayData.bendingTimesDay || '0',
      };
    }
  } catch (error) {
    console.error('获取日数据失败:', error);
    // 处理错误，但不显示toast，因为这只是辅助数据
  }
};

// 格式化选中日期
const formatSelectedDate = () => {
  if (!selectedDate.value) return '';
  const parts = selectedDate.value.split('.');
  if (parts.length < 3) return '';
  return `${parts[0]}-${parts[1]}-${parts[2]}`;
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const parts = dateStr.split('.');
  if (parts.length < 3) return dateStr;
  return parts[2]; // 只返回日期部分
};

// 初始化图表
const initChart = () => {
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }

  if (!chartRef.value || !rideData.value?.rideRocordList) return;

  chartInstance.value = echarts.init(chartRef.value);

  // 准备图表数据
  const dates = rideData.value.rideRocordList.map(item => formatDate(item.date));
  const values = rideData.value.rideRocordList.map(item => parseFloat(item.rideMileage || 0));

  // 计算Y轴最大值，确保有足够的高度
  const maxValue = Math.max(...values);
  const yMax = maxValue < 60 ? 60 : Math.ceil(maxValue * 1.2); // 最小高度为60，否则增加20%

  // 计算刻度值
  let interval = 15;

  // 创建渐变色
  const activeItemColor = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    { offset: 0, color: '#4361ee' },
    { offset: 1, color: '#3a0ca3' }
  ]);

  const normalItemColor = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    { offset: 0, color: '#e6e7ff' },
    { offset: 1, color: '#dadcff' }
  ]);

  // 为选中日期准备特殊样式
  const markPoint = selectedDayIndex.value >= 0 ? {
    data: [{
      coord: [selectedDayIndex.value, values[selectedDayIndex.value]],
      value: values[selectedDayIndex.value],
      itemStyle: {
        color: activeItemColor
      },
      symbolSize: 0,
      label: { show: false }
    }],
    symbol: 'circle',
    symbolSize: 0
  } : {};

  const option = {
    grid: {
      left: '10%',
      right: '6%',
      bottom: '12%',
      top: '15%',
      containLabel: false
    },
    dataZoom: [
      {
        type: 'inside',
        start: dates.length > 10 ? Math.max(0, 100 - (10 / dates.length * 100)) : 0, // 如果数据点多，默认显示最后10个
        end: 100,
        zoomLock: false,
        throttle: 100,
        minSpan: Math.min(100, Math.max(20, 700 / dates.length))  // 动态计算最小显示比例
      },
      {
        type: 'slider',
        show: false, // 隐藏滚动条但保留功能
        height: 20,
        bottom: 0,
        start: dates.length > 10 ? Math.max(0, 100 - (10 / dates.length * 100)) : 0,
        end: 100
      }
    ],
    xAxis: {
      type: 'category',
      data: dates,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#eaeaea'
        }
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#666',
        fontSize: 12,
        fontWeight: 400,
        margin: 10
      }
    },
    yAxis: {
      type: 'value',
      name: 'km',
      nameTextStyle: {
        padding: [0, 0, 0, 5],
        fontSize: 12,
        color: '#999'
      },
      max: yMax,
      interval: interval,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#f5f5f5',
          type: 'dashed',
          width: 1
        }
      },
      axisLabel: {
        color: '#999',
        fontSize: 12,
        formatter: function (value) {
          return value === 0 ? '0' : value;
        }
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        const data = params[0];
        return `${data.name}日: ${data.value} km`;
      },
      backgroundColor: 'rgba(50, 50, 50, 0.7)',
      borderWidth: 0,
      textStyle: {
        color: '#fff'
      },
      position: function (pos, params, dom, rect, size) {
        return [pos[0] - 30, pos[1] - 60]; // 在柱状图上方显示
      },
      extraCssText: 'border-radius:4px; padding: 6px 10px;'
    },
    series: [{
      type: 'bar',
      data: values,
      barWidth: '50%',
      itemStyle: {
        color: function (params) {
          // 选中的日期使用特殊颜色
          return params.dataIndex === selectedDayIndex.value ? activeItemColor : normalItemColor;
        },
        borderRadius: [4, 4, 0, 0]
      },
      markPoint: markPoint,
      emphasis: {
        itemStyle: {
          color: activeItemColor
        }
      },
      animation: true,
      animationDuration: 600,
      animationEasing: 'elasticOut',
      label: {
        show: true,
        position: 'top',
        fontSize: 10,
        color: '#666',
        formatter: function (params) {
          const val = parseFloat(params.value);
          return val > 0 ? val.toFixed(1) : '';
        },
        distance: 5
      }
    }]
  };

  chartInstance.value.setOption(option);

  // 注册点击事件
  chartInstance.value.on('click', async (params) => {
    if (params.componentType === 'series') {
      selectedDayIndex.value = params.dataIndex;
      selectedDate.value = rideData.value.rideRocordList[params.dataIndex].date;

      // 获取选中日期的详细数据
      await fetchDayData(selectedDate.value);

      // 更新图表
      // initChart();
    }
  });

  // 自适应大小
  window.addEventListener('resize', () => {
    chartInstance.value && chartInstance.value.resize();
  });
};

// 计算雷达图数据
const calculateRadarData = () => {
  if (!rideData.value) return null;

  const minutes = parseFloat(rideData.value?.ridingTimeMonthUnitMinute || 0);
  return {
    maxSpeed: parseFloat(rideData.value?.maxSpeedMonth || rideData.value?.maxSpeed || 0),
    avgSpeed: parseFloat(rideData.value?.avgVelocityMonth || 0),
    mileage: parseFloat(rideData.value?.rideMileageMonth || 0),
    // 转小时，保留 1 位小数
    ridingTime: +(minutes / 60).toFixed(1),
    // 仅使用本月统计，避免点击日柱影响雷达
    bendings: parseFloat(rideData.value?.bendingTimesMonth || 0),
    acceleration: parseFloat(rideData.value?.accelerationTimesMonth || 0),
  };
};

// 初始化雷达图
const initRadarChart = (container, isPreview = false) => {
  const chartContainer = container;
  if (!chartContainer) return;

  // 如果已经存在图表实例，销毁它
  let chartInstance = isPreview ? previewChartInstance : radarChartInstance;
  if (chartInstance) {
    chartInstance.dispose();
  }

  // 创建新的图表实例
  chartInstance = echarts.init(chartContainer);
  if (isPreview) {
    previewChartInstance = chartInstance;
  } else {
    radarChartInstance = chartInstance;
  }

  const data = calculateRadarData();
  if (!data) return;

  // 动态计算“漂亮”的最大值，按数量级上取 1.2 倍
  const niceMax = (v) => {
    const x = Number(v) || 0;
    if (x <= 0) return 10;
    const e = Math.floor(Math.log10(x));
    const base = Math.pow(10, e);
    const mult = Math.ceil((x * 1.2) / base);
    return mult * base;
  };

  const defs = [
    { key: 'maxSpeed', label: '最高速度', unit: 'km/h' },
    { key: 'avgSpeed', label: '平均速度', unit: 'km/h' },
    { key: 'mileage', label: '骑行里程', unit: 'km' },
    { key: 'ridingTime', label: '骑行时长', unit: 'h' },
    { key: 'bendings', label: '压弯技巧', unit: '次' },
    { key: 'acceleration', label: '加速能力', unit: '次' }
  ];

  const values = defs.map(d => Number(data[d.key] || 0));
  const indicatorWithValues = defs.map((d, i) => ({
    name: `${d.label}\n${values[i]} ${d.unit}`,
    max: niceMax(values[i])
  }));

  const option = {
    backgroundColor: 'transparent',
    color: ['#4361ee'],
    grid: {
      left: '10%',
      right: '6%',
      bottom: '12%',
      top: '15%',
      containLabel: false
    },
    radar: {
      indicator: indicatorWithValues,
      center: ['50%', '50%'],
      radius: isPreview ? '65%' : '62%',
      splitNumber: 5,
      shape: 'polygon',

      axisName: {
        formatter: (name) => {
          const parts = String(name).split('\n');
          const t = parts[0] || '';
          const v = parts[1] || '';
          return `{t|${t}}\n{v|${v}}`;
        },
        color: '#2b2d42',
        lineHeight: 18,
        padding: [2, 2],
        // distance: 8,
        rotate: 0,
        rich: {
          t: { fontSize: isPreview ? 12 : 13, fontWeight: 550, color: '#1f2937' },
          v: { fontSize: isPreview ? 11 : 12, color: '#4b5563' }
        }
      },

      splitArea: {
        show: true,
        areaStyle: {
          color: [
            'rgba(67, 97, 238, 0.04)',
            'rgba(67, 97, 238, 0.08)',
            'rgba(67, 97, 238, 0.12)',
            'rgba(67, 97, 238, 0.16)'
          ],
          shadowColor: 'rgba(0,0,0,0.05)',
          shadowBlur: 4
        }
      },

      axisLine: {
        lineStyle: {
          color: 'rgba(67, 97, 238, 0.3)',
          width: 1
        }
      },

      splitLine: {
        lineStyle: {
          color: 'rgba(67, 97, 238, 0.35)',
          width: 1,
          type: 'solid'
        }
      }
    },

    series: [
      {
        type: 'radar',
        name: '骑行能力',
        data: [
          {
            value: values,
            name: '骑行能力',
            symbol: 'circle',
            symbolSize: isPreview ? 4 : 5,
            itemStyle: {
              color: '#4361ee',
              borderColor: '#fff',
              borderWidth: 2,
              shadowColor: 'rgba(67, 97, 238, 0.5)',
              shadowBlur: 8
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(67, 97, 238, 0.7)' },
                { offset: 0.6, color: 'rgba(67, 97, 238, 0.3)' },
                { offset: 1, color: 'rgba(67, 97, 238, 0.1)' }
              ]),
              opacity: 0.8
            },
            lineStyle: {
              color: '#4361ee',
              width: 3,
              shadowColor: 'rgba(67, 97, 238, 0.3)',
              shadowBlur: 6
            }
          }
        ],
        animationDuration: 1200,
        animationEasing: 'cubicOut'
      }
    ]
  };

  option.tooltip = {
    show: true,
    trigger: 'item',
    backgroundColor: 'rgba(17,24,39,0.85)',
    borderWidth: 0,
    textStyle: { color: '#fff', fontSize: 10 },
    className: 'radar-tooltip',
    formatter: () => {
      return [
        `最高速度：${(data.maxSpeed || 0)} km/h`,
        `平均速度：${(data.avgSpeed || 0)} km/h`,
        `骑行里程：${(data.mileage || 0)} km`,
        `骑行时长：${(data.ridingTime || 0)} min`,
        `压弯技巧：${(data.bendings || 0)} 次`,
        `加速能力：${(data.acceleration || 0)} 次`
      ].join('<br/>');
    }
  };

  chartInstance.setOption(option);
};

// 计算本月总里程
const calculateMonthlyMileage = () => {
  if (!rideData.value?.rideRocordList || rideData.value.rideRocordList.length === 0) return '0';

  const total = rideData.value.rideRocordList.reduce((sum, item) => {
    return sum + parseFloat(item.rideMileage || 0);
  }, 0);

  return total.toFixed(1);
};

// 格式化骑行时间
const formatRidingTime = (minutes) => {
  if (minutes === null || minutes === undefined) return '0 min';
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  return `${hours}h ${remainingMinutes}min`;
};

// 保存图片
const saveImage = async () => {
  if (!sharePreviewRef.value) return;

  try {
    showLoadingToast({
      message: '生成图片中...',
      forbidClick: true,
      duration: 0,
    });

    // 确保雷达图已经渲染
    await nextTick();

    // 确保车辆图片可被 html2canvas 捕获（转为 dataURL 防止跨域）
    await ensureVehicleImageReady();
    // 确保头像图片也通过后端代理转为 dataURL，避免污染
    await ensureAvatarImageReady();

    // 截取预览区域为图片
    const canvas = await html2canvas(sharePreviewRef.value, {
      useCORS: true,
      scale: 3,
      backgroundColor: '#fff',
      allowTaint: false,
      imageTimeout: 8000,
      logging: false
    });

    const fileName = '我的骑行能力图谱.png';

    // 优先使用 Blob，避免将 dataURL 当作文件路径被某些环境误处理
    await new Promise((resolve, reject) => {
      try {
        canvas.toBlob(async (blob) => {
          try {
            if (!blob) {
              // 回退到 dataURL 方式
              const dataUrl = canvas.toDataURL('image/png');
              const a = document.createElement('a');
              a.href = dataUrl;
              a.download = fileName;
              document.body.appendChild(a);
              a.click();
              document.body.removeChild(a);
              return resolve();
            }

            // Edge (旧版) 兼容
            const navAny = window.navigator;
            if (navAny && typeof navAny.msSaveOrOpenBlob === 'function') {
              navAny.msSaveOrOpenBlob(blob, fileName);
              return resolve();
            }

            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = fileName;
            // iOS/Safari 可能不支持 download 属性，尝试打开新窗口
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            setTimeout(() => URL.revokeObjectURL(url), 2000);
            resolve();
          } catch (err) {
            reject(err);
          }
        }, 'image/png');
      } catch (e) {
        reject(e);
      }
    });

    showSuccessToast('图片已保存');
  } catch (error) {
    console.error('生成图片失败:', error);
    showFailToast('保存图片失败');
  } finally {
    closeToast();
  }
};

// 通过后端图片代理拉取并转为 dataURL，避免跨域污染
const proxyToDataURL = async (rawUrl) => {
  const proxied = `/api/proxy/image?url=${encodeURIComponent(rawUrl)}`;
  const resp = await fetch(proxied, { cache: 'no-store' });
  if (!resp.ok) throw new Error('proxy fetch failed');
  const blob = await resp.blob();
  const reader = new FileReader();
  return await new Promise((resolve, reject) => {
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(blob);
  });
};

// 处理车辆图片跨域，转成 dataURL
const ensureVehicleImageReady = async () => {
  const el = vehicleImgRef.value;
  if (!el) return;
  const src = el.getAttribute('src');
  if (!src || src.startsWith('data:') || src.startsWith('blob:')) return;
  try {
    el.crossOrigin = 'anonymous';
    const dataUrl = await proxyToDataURL(src);
    el.src = dataUrl;
    await new Promise((r) => { el.onload = () => r(); });
  } catch (e) {
    // 若失败则退回本地占位图，保证导出不中断
    el.src = defaultVehicleImg;
    await new Promise((r) => { el.onload = () => r(); });
  }
};

// 处理头像图片，转成 dataURL（若存在头像）
const ensureAvatarImageReady = async () => {
  const el = avatarImgRef.value;
  if (!el) return; // 头像可能不存在（使用首字母占位）
  const src = el.getAttribute('src');
  if (!src || src.startsWith('data:') || src.startsWith('blob:')) return;
  try {
    el.crossOrigin = 'anonymous';
    const dataUrl = await proxyToDataURL(src);
    el.src = dataUrl;
    await new Promise((r) => { el.onload = () => r(); });
  } catch (_) {
    // 头像失败不阻断导出，改为隐藏头像，展示占位
    try { el.src = ''; } catch { }
  }
};

// 打开分享预览
watch(showShareModal, (show) => {
  if (show) {
    (async () => {
      try {
        showLoadingToast({ message: '准备数据中...', duration: 0, forbidClick: true });
        await ensureMonthAggregates();
      } finally {
        closeToast();
        nextTick(() => {
          initRadarChart(previewChartRef.value, true);
        });
      }
    })();
  }
});

// 监听数据变化，更新雷达图
watch(rideData, () => {
  nextTick(() => {
    if (radarChartRef.value) {
      initRadarChart(radarChartRef.value);
    }
  });
}, { deep: true });

// 初始化
onMounted(async () => {
  // 检查是否有指定的车辆
  const { vinNo } = route.query;
  if (vinNo) {
    // 先获取初始数据
    await fetchMileageData();
    // 计算本月聚合，保证首次渲染雷达图就有数据
    try {
      await ensureMonthAggregates();
    } catch (_) { }

    // 初始化雷达图
    nextTick(() => {
      initRadarChart(radarChartRef.value);
    });
  } else {
    // 如果没有指定车辆，则返回首页
    router.replace('/');
  }

  // 监听窗口大小变化
  window.addEventListener('resize', onResize);
});

onUnmounted(() => {
  // 清理图表实例，避免内存泄漏
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }
  if (radarChartInstance) {
    radarChartInstance.dispose();
  }
  if (previewChartInstance) {
    previewChartInstance.dispose();
  }
  window.removeEventListener('resize', onResize);
});
</script>

<style lang="scss" scoped>
.mileage-detail-page {
  height: 100%;
  background-color: #f7f7fa;
  padding-top: 50px;
  /* 仅纵向滚动，防止横向内容飞出 */
  overflow-y: auto;
  overflow-x: hidden;

  // 隐藏滚动条
  &::-webkit-scrollbar {
    display: none;
  }
}

.page-header {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 15px 16px;
  position: relative;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  .back-icon {
    position: absolute;
    left: 16px;
    top: 50%;
    transform: translateY(-50%);
    color: #333;
    cursor: pointer;

    &:active {
      opacity: 0.7;
    }
  }

  .page-title {
    flex: 1;
    text-align: center;
    font-size: 18px;
    font-weight: 600;
    color: #111;
  }
}

.nav-cards {
  display: flex;
  background-color: #fff;
  padding: 15px 0 12px;
  margin-bottom: 12px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  .nav-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .nav-icon {
      width: 44px;
      height: 44px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 6px;
      color: #4361ee;
      background-color: #f0f4ff;
      border-radius: 50%;

      &:active {
        background-color: #e6ebff;
      }
    }

    .nav-text {
      font-size: 14px;
      color: #333;
      font-weight: 500;
    }
  }
}

.data-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin: 0 12px 12px;
  overflow: hidden;
}

.total-stats {
  display: flex;
  padding: 12px 7px;

  .total-stat {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;

    .stat-value {
      font-size: 20px;
      font-weight: 700;
      color: #111;
      margin-bottom: 2px;

      .unit {
        font-size: 14px;
        font-weight: normal;
        margin-left: 2px;
        color: #666;
      }
    }

    .stat-label {
      font-size: 13px;
      color: #666;
    }
  }

  .stat-divider {
    width: 1px;
    height: 40px;
    background-color: #eee;
    margin: 0 20px;
    align-self: center;
  }
}

.chart-section {
  padding: 10px;

  .month-selector {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 5px;

    .month-arrow {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      color: #4361ee;
      border-radius: 50%;

      &:active {
        background-color: #f0f4ff;
        transform: scale(0.95);
      }
    }

    .current-month {
      font-size: 16px;
      font-weight: 600;
      margin: 0 15px;
      color: #333;
      min-width: 80px;
      text-align: center;
    }
  }

  .chart-container {
    height: 220px;

    .loading-chart {
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #666;
      font-size: 14px;

      .loading-spinner {
        width: 30px;
        height: 30px;
        border: 3px solid #f0f4ff;
        border-top: 3px solid #4361ee;
        border-radius: 50%;
        margin-bottom: 10px;
        animation: spin 1s linear infinite;
      }

      @keyframes spin {
        0% {
          transform: rotate(0deg);
        }

        100% {
          transform: rotate(360deg);
        }
      }
    }

    .no-data {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #999;
      font-size: 14px;
    }

    .chart {
      height: 100%;
      width: 100%;
    }
  }
}

.day-data {
  .card-header {
    padding: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }

    .card-date {
      font-size: 14px;
      color: #4361ee;
      font-weight: 500;
    }
  }

  .day-stats-row {
    display: flex;
    padding: 10px 0;

    &:not(:last-child) {
      border-bottom: 1px solid #f0f0f0;
    }

    .day-stat {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;

      .day-stat-value {
        font-size: 20px;
        font-weight: 700;
        color: #333;

        .unit {
          font-size: 12px;
          font-weight: normal;
          margin-left: 2px;
          color: #666;
        }
      }

      .day-stat-label {
        font-size: 13px;
        color: #666;
      }
    }
  }
}

// 雷达图部分
.radar-chart-section {
  padding: 16px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }

    .share-button {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #4361ee;
      cursor: pointer;

      svg {
        margin-right: 4px;
      }

      &:active {
        opacity: 0.8;
      }
    }
  }

  .radar-container {
    height: 280px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: transparent;
    border-radius: 8px;
    overflow: hidden;

    .radar-chart {
      width: 100%;
      height: 100%;
    }
  }

  .chart-description {
    margin-top: 10px;
    text-align: center;
    font-size: 12px;
    color: #666;
  }
}

// 分享预览弹窗
.share-popup {
  overflow: hidden;
  border-top-left-radius: 16px;
  border-top-right-radius: 16px;

  .share-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #eee;

    .share-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }

    .close-button {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      background-color: #f5f5f5;
      cursor: pointer;

      &:active {
        background-color: #e5e5e5;
      }
    }
  }

  .share-content {
    display: flex;
    flex-direction: column;
    height: calc(100% - 64px);

    .preview-container {
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
      display: flex;
      justify-content: center;
      background-color: #f5f5f5;

      .preview-image-container {
        background: linear-gradient(180deg, #ffffff 0%, #f9fbff 100%);
        padding: 15px 15px 11px;
        box-shadow: 0 10px 24px rgba(67, 97, 238, 0.12), 0 2px 8px rgba(0, 0, 0, 0.06);
        width: 100%;
        box-sizing: border-box;
        border: 1px solid #eef1ff;
        overflow: hidden;

        .preview-header {
          text-align: center;
          margin-bottom: 6px;

          .preview-title {
            font-size: 20px;
            font-weight: 700;
            margin-bottom: 10px;
            color: #2b2d42;
          }

          .vehicle-block {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            padding: 6px 8px;
            border: 1px solid #eef1ff;
            border-radius: 12px;
            background: #f9fbff;



            .preview-vehicle {
              font-size: 16px;
              font-weight: 700;
              color: #666;
            }

            .left {
              display: flex;
              align-items: center;
              gap: 10px;
            }

            .right {
              display: flex;
              align-items: center;
            }

            .user-info {
              display: flex;
              align-items: center;
              gap: 10px;
            }

            .avatar-wrap {
              width: 44px;
              height: 44px;
              border-radius: 50%;
              overflow: hidden;
              display: flex;
              align-items: center;
              justify-content: center;
              background: #eef1ff;
              border: 1px solid #e8eaff;
            }

            .user-avatar {
              width: 44px;
              height: 44px;
              border-radius: 50%;
              object-fit: cover;
              border: 1px solid #e8eaff;
              background: #fff;
            }

            .avatar-fallback {
              width: 100%;
              height: 100%;
              display: flex;
              align-items: center;
              justify-content: center;
              color: #3559ff;
              font-weight: 700;
            }

            .user-meta {
              display: flex;
              flex-direction: column;
              align-items: flex-start;
              line-height: 1.1;
            }

            .user-name {
              font-size: 14px;
              font-weight: 700;
              color: #2b2d42;
            }

            .user-badge {
              margin-left: 6px;
              font-size: 12px;
              font-weight: 600;
              color: #3559ff;
              background: #eef1ff;
              border: 1px solid #e1e6ff;
              padding: 2px 6px;
              border-radius: 999px;
              vertical-align: middle;
            }

            .user-sub {
              margin-top: 2px;
              font-size: 12px;
              color: #8a8fa3;
            }
          }
        }

        .preview-chart-container {
          height: 310px;
          margin-bottom: 10px;
        }

        .meta-line {
          margin-top: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8px;

          .pill {
            font-size: 12px;
            color: #3559ff;
            background: #eef1ff;
            border: 1px solid #e1e6ff;
            padding: 2px 8px;
            border-radius: 999px;
          }

          .dot {
            width: 4px;
            height: 4px;
            background: #c9cde6;
            border-radius: 50%;
          }

          .vin {
            font-size: 12px;
            color: #8a8fa3;
          }
        }

        .highlight-stats {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 10px;
          margin: 12px 0 6px;

          .h-item {
            display: flex;
            align-items: center;
            gap: 8px;
            background: #f8f9ff;
            border: 1px solid #eef1ff;
            border-radius: 10px;
            padding: 8px 10px;

            .h-ic {
              width: 18px;
              height: 18px;
              color: #4361ee;
              flex: 0 0 18px;
            }

            .h-text {
              font-size: 12px;
              color: #5a5f7a;

              b {
                font-size: 16px;
                color: #2b2d42;
                margin-right: 2px;
              }

              .unit {
                display: block;
                line-height: 1.1;
                color: #6b7280;
                margin-top: 2px;
              }

              .label {
                display: block;
                line-height: 1.1;
                color: #8a8fa3;
                margin-top: 2px;
              }
            }
          }
        }

        .preview-stats {
          background-color: #f6f7fe;
          border-radius: 12px;
          padding: 12px 14px;
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 12px;

          .preview-stat-item {
            .preview-stat-label {
              font-size: 12px;
              color: #666;
              margin-bottom: 2px;
            }

            .preview-stat-value {
              font-size: 15px;
              font-weight: 600;
              color: #2b2d42;
            }
          }
        }

        .preview-footer {
          margin-top: 14px;
          font-weight: 600;
          font-size: 12px;
          color: #4a4d5c;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 6px;
          
          .footer-logo {
            width: 18px;
            height: 18px;
            // vertical-align: middle;
            object-fit: contain;
            margin-top: 3px;
            border-radius: 3px;
          }
        }
      }
    }

    .share-actions {
      padding: 16px;
      border-top: 1px solid #eee;
    }
  }
}

.preview-vehicle-img {
  width: 100px;
  object-fit: cover;
  border-radius: 8px;
  // border: 1px solid #e8eaff;
  // background: #fff;
}
</style>